package cn.team11.smarteye.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ViewSwitcher;

import com.eques.icvss.utils.ResultCode;
import com.jakewharton.rxbinding2.view.RxView;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTouch;
import cn.team11.sds.dayi.R;
import cn.team11.smarteye.base.BaseActivity;
import cn.team11.smarteye.bean.CateyeEvent;
import cn.team11.smarteye.contract.VideoCallContract;
import cn.team11.smarteye.impl.VideoCallPresenterImpl;
import cn.team11.smarteye.misc.SConstants;
import cn.team11.smarteye.utils.AppLogger;
import cn.team11.smarteye.utils.ToastUtil;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Murphy on 2017/11/3.
 */

public class VideoCallActivity extends BaseActivity<VideoCallContract.Presenter> implements VideoCallContract.View, SurfaceHolder.Callback{

    @BindView(R.id.video_view_switcher)
    ViewSwitcher mViewSwitcher;

    @BindView(R.id.video_surfaceview)
    SurfaceView mVideoSurfaceView;
    @BindView(R.id.device_nick_name)
    TextView mDeviceNickTv;
    @BindView(R.id.connected_time)
    TextView mVideoTimeTv;
    @BindView(R.id.mute_bt)
    TextView mMuteBt;
    @BindView(R.id.screen_shot)
    TextView mShotBt;


    private SurfaceHolder mHolder;
    private String uid;
    private String nick;
    private String name;
    private String callId;

    private Disposable mTimeCountDisposable;
    private Disposable mTimeoutDisposables;
    private boolean isAudioOnly;
    private boolean isFromIncoming = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_call);
        ButterKnife.bind(this);
        init();
    }

    @Override
    public void init() {

        mVideoSurfaceView.setZOrderOnTop(true);

        mHolder = mVideoSurfaceView.getHolder();
        mHolder.addCallback(this);

        uid = getIntent().getStringExtra(SConstants.UID);
        nick = getIntent().getStringExtra(SConstants.NICKNAME);
        name = getIntent().getStringExtra(SConstants.NAME);
        if (nick == null || StringUtils.isEmpty(nick)){
            nick = getResources().getString(R.string.smart_cateye);
        }
        mDeviceNickTv.setText(nick);

        isAudioOnly = getIntent().getBooleanExtra(SConstants.IS_AUDIO_ONLY, false);
        isFromIncoming = getIntent().getBooleanExtra(SConstants.FROM_INCOMING, false);

        if (uid == null || StringUtils.isEmpty(uid)) {
            AppLogger.e("devices uid is null!!!");
            finish();
        }
        //初始化presenter
        new VideoCallPresenterImpl(this);

        RxView.clicks(mMuteBt)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (mBasePresenter != null){
                            if (mMuteBt.isSelected()){//当前为静音，点击切换外放
                                mBasePresenter.setAudioMute(callId, false);
                            } else {//当前为外放，点击切换静音
                                mBasePresenter.setAudioMute(callId, true);
                            }
                        }
                    }
                });

        RxView.clicks(mShotBt)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (mBasePresenter != null){
                            String fileName = SConstants.SCREENSHOT_PATH + File.separator +
                                    name + File.separator + System.currentTimeMillis() + ".jpg";
                            File file = new File(fileName);
                            if(!file.getParentFile().exists()){
                                file.getParentFile().mkdirs();
                            }
                            mBasePresenter.screenShot(fileName);
                            showToast(ToastUtil.NORMAL_TOAST, String.format(getResources().getString(R.string.screen_snap_tips), fileName));
                        }
                    }
                });
    }

    @Override
    public void onLoginResult(boolean result) {

    }

    @Override
    public void onNetAvailable(boolean isAvailable) {

    }

    @Override
    public void onCateyeServiceBinded() {

    }

    @Override
    public void setPresenter(VideoCallContract.Presenter presenter) {
        this.mBasePresenter = presenter;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @OnClick({R.id.wainting_hang_up,
            R.id.calling_hang_up})
    public void onClickAction(View view){
        switch (view.getId()){
            case R.id.wainting_hang_up:
            case R.id.calling_hang_up:
                hangUpCall();
                break;
        }

    }

    @OnTouch (R.id.speak_bt)
    public boolean onTouchAction(View v, MotionEvent event){
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                ((Button)v).setText(getResources().getString(R.string.done_after_release));
                v.setPressed(true);
                AppLogger.i("开始说话");
                ((Button) v).setTextColor(ContextCompat.getColor(this, R.color.color_white));
                if (mBasePresenter != null){
                    mBasePresenter.enableSpeaker(callId, true);
                }
                break;
            case MotionEvent.ACTION_UP:
                AppLogger.i("说话结束");
                ((Button)v).setText(getResources().getString(R.string.speak_with_pressing));
                ((Button) v).setTextColor(ContextCompat.getColor(this, R.color.color_33000000));
                v.setPressed(false);
                if (mBasePresenter != null){
                    mBasePresenter.enableSpeaker(callId, false);
                }
                break;
        }
        return true;
    }

    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
        hangUpCall();
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        AppLogger.i("json-surface surfaceCreated");
        //开始视频
        if (mBasePresenter != null){
            if (isAudioOnly){//语音通话
                Drawable iconDrawable = ContextCompat.getDrawable(this, R.drawable.ic_listen_logo);
                callId = mBasePresenter.openAudioCall(uid, mVideoSurfaceView, iconDrawable, true);
                mShotBt.setVisibility(View.INVISIBLE);
            } else {//视频通话
                mShotBt.setVisibility(View.VISIBLE);
                callId = mBasePresenter.openVideoCall(uid, mHolder.getSurface(), false);
            }
            mBasePresenter.setAudioMute(callId, false);
            if (!isFromIncoming){
                mViewSwitcher.showNext();
                //启动计时器,超时则退出
                createTimer();
            }
            if (callId == null) {
                AppLogger.e("callid is null");
                finish();
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        AppLogger.i("json-surface surfaceChanged");

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        AppLogger.i("json-surface surfaceDestroyed");

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoCallCloseResult(CateyeEvent.VideoCallCloseEvent event){
        if (event.getResultCode() == ResultCode.SUCCESS){
            showToast(ToastUtil.POSITIVE_TOAST, "连接断开");
            finish();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onVideoPlayStatusNow(CateyeEvent.VideoStatusEvent event){
        if (event.getStatus() == SConstants.VIDEO_PLAY){
            if (!isFromIncoming)
                mViewSwitcher.showPrevious();//显示播放界面
            mVideoTimeTv.setVisibility(View.VISIBLE);
            if (mTimeoutDisposables != null && !mTimeoutDisposables.isDisposed()) mTimeoutDisposables.dispose();
            //开始计时
            if (mBasePresenter != null){
                mTimeCountDisposable = mBasePresenter.countVideoTime()
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<String>() {
                            @Override
                            public void accept(String s) throws Exception {
                                mVideoTimeTv.setText(s);
                            }
                        });
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (!mTimeCountDisposable.isDisposed()){
            mTimeCountDisposable.dispose();
        }
        if (!mTimeoutDisposables.isDisposed()){
            mTimeoutDisposables.dispose();
        }
        hangUpCall();
    }


    private void hangUpCall(){
        if (mBasePresenter != null && !StringUtils.isEmpty(callId)){
            mBasePresenter.hangupVideoCall(callId);
        }
        sendCloseBroadcast();
        finish();
    }

    @Override
    public void updateMuteBtState(boolean state) {
        mMuteBt.setSelected(state);
    }

    @Override
    public void updateScreenShotState(boolean state) {
        mShotBt.setSelected(state);
    }



    private void createTimer(){
        mTimeoutDisposables = Observable.interval(0, 1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long aLong) throws Exception {
                if (aLong == 30){//timeout
                    showToast(ToastUtil.NEGATIVE_TOAST, getString(R.string.call_connect_timeout));
                    mTimeoutDisposables.dispose();
                    hangUpCall();
                }
            }
        });
    }


    @Subscribe (threadMode = ThreadMode.MAIN)
    public void onPhoneStateListener(CateyeEvent.PhoneCallEvent event){
        if (event.getState() == TelephonyManager.CALL_STATE_RINGING){//来电
            hangUpCall();
        }
    }
    @Subscribe (threadMode = ThreadMode.MAIN)
    public void onAnotherCallEvent(CateyeEvent.CloseCurrentCallEvent event){
        if (mBasePresenter != null){
            hangUpCall();
        }
    }

    private void sendCloseBroadcast(){
        Intent intent = new Intent();
        intent.setAction(SConstants.INCOMING_CLOSE_ACTION);
        sendBroadcast(intent);
    }
}
